    package com.cpos.base.Netty.handler.netty.handler;

    import io.netty.bootstrap.ServerBootstrap;
    import io.netty.channel.ChannelFuture;
    import io.netty.channel.ChannelInitializer;
    import io.netty.channel.EventLoopGroup;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.SocketChannel;
    import io.netty.channel.socket.nio.NioServerSocketChannel;

    import java.net.InetSocketAddress;

    /*
*  Echo服务器
* */
public class EchoServer {
    private final int port;


    public EchoServer(int port) {
       this.port = port;
    }

    public static void main(String[] args) throws Exception {
        System.err.println("Usage"+ EchoServer.class.getSimpleName() + "<port>" );
        int port = 8999;
        new EchoServer(port).start();
    }

    //启动方法
    //创建一个ServerBootstap实例以引导和绑定服务器
    private void start() throws Exception {
        final EchoServerHandler serverHandler = new EchoServerHandler();
        //创建并分配一个NioEventLoopGroup实例以进行事件的处理，如接受新连接以及读写数据
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            //指定服务器绑定的本地的InetSocketAddress；
            ServerBootstrap s = new ServerBootstrap();
            s.group(group).channel(NioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress(port)).childHandler(new ChannelInitializer<SocketChannel>() {
                       //使用一个Handler实例初始化新的Channel；
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast(serverHandler);
                }
            });
            //调用ServerBootstap.bind()方法以绑定服务器
            ChannelFuture sync = s.bind().sync();
            sync.channel().closeFuture().sync();
        }finally {
            group.shutdownGracefully().sync();
        }
    }
}


